/**
 * 演示 componentDidUpdate 的使用 - 聊天对话框效果
 */
import React, { Component } from "react";

export default class Message extends Component {
  //声明状态
  state = {
    msgs: [],
  };

  send = () => {
    //获得 input 的值
    let v = this.input.value;
    //设置文本
    this.setState({
      msgs: [...this.state.msgs, v]
    })
    
  }

  render() {
    return (
      <div>
        <input ref={el => this.input = el} type="text" />
        <button onClick={this.send}>发送</button>
        <hr />
        <div
          id="result"
          ref={el => this.result = el}
          style={{ width: 400, height: 300, border: "solid 1px #666", overflowY: 'scroll' }}
        >
          <ul>
            {this.state.msgs.map((item, index) => {
              return <li key={index}>{item}</li>;
            })}
          </ul>
        </div>
      </div>
    );
  }

  componentDidUpdate(){
    //修改 result div 元素垂直方向的滚动距离
    this.result.scrollTop = this.result.scrollHeight;
  }
}
